package com.demo.las.service;

import com.demo.las.entity.StudentStudyRecord;
import com.demo.las.repository.StudentStudyRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class StudentStudyRecordService {

    @Autowired
    private StudentStudyRecordRepository repository;

    public StudentStudyRecord create(String studentName,
                                     String studentNo,
                                     String courseName,
                                     String knowledgePoint,
                                     LocalDateTime startTime,
                                     Integer durationMinutes) {
        StudentStudyRecord r = new StudentStudyRecord();
        r.setStudentName(studentName);
        r.setStudentNo(studentNo);
        r.setCourseName(courseName);
        r.setKnowledgePoint(knowledgePoint);
        r.setStartTime(startTime);
        r.setDurationMinutes(durationMinutes);
        r.setCreatedAt(LocalDateTime.now());
        return repository.save(r);
    }

    public List<StudentStudyRecord> list(String studentName,
                                         String studentNo,
                                         String courseName,
                                         String knowledgePoint) {
        return repository.findAll().stream()
                .filter(r -> studentName == null || studentName.isBlank() || (r.getStudentName()!=null && r.getStudentName().contains(studentName)))
                .filter(r -> studentNo == null || studentNo.isBlank() || (r.getStudentNo()!=null && r.getStudentNo().contains(studentNo)))
                .filter(r -> courseName == null || courseName.isBlank() || (r.getCourseName()!=null && r.getCourseName().contains(courseName)))
                .filter(r -> knowledgePoint == null || knowledgePoint.isBlank() || (r.getKnowledgePoint()!=null && r.getKnowledgePoint().contains(knowledgePoint)))
                .sorted((a,b) -> b.getStartTime().compareTo(a.getStartTime()))
                .collect(Collectors.toList());
    }

    public static class OverviewItem {
        public String studentName;
        public String studentNo;
        public Integer totalRecords;
        public Integer totalDurationMinutes;
        public Double avgDurationMinutes;
        public LocalDateTime earliestStart;
        public LocalDateTime latestStart;
        public Integer coursesCount;
    }

    public List<OverviewItem> overview() {
        List<StudentStudyRecord> all = repository.findAll();
        Map<String, List<StudentStudyRecord>> grouped = all.stream()
                .collect(Collectors.groupingBy(r -> (r.getStudentNo()==null?"":r.getStudentNo()) + "|" + (r.getStudentName()==null?"":r.getStudentName())));
        List<OverviewItem> result = new ArrayList<>();
        for (Map.Entry<String,List<StudentStudyRecord>> e : grouped.entrySet()) {
            List<StudentStudyRecord> list = e.getValue();
            OverviewItem item = new OverviewItem();
            item.studentNo = list.get(0).getStudentNo();
            item.studentName = list.get(0).getStudentName();
            item.totalRecords = list.size();
            int total = list.stream().map(r -> r.getDurationMinutes()==null?0:r.getDurationMinutes()).mapToInt(Integer::intValue).sum();
            item.totalDurationMinutes = total;
            item.avgDurationMinutes = list.isEmpty()?0.0: total * 1.0 / list.size();
            item.earliestStart = list.stream().map(StudentStudyRecord::getStartTime).filter(Objects::nonNull).min(LocalDateTime::compareTo).orElse(null);
            item.latestStart = list.stream().map(StudentStudyRecord::getStartTime).filter(Objects::nonNull).max(LocalDateTime::compareTo).orElse(null);
            item.coursesCount = (int)list.stream().map(StudentStudyRecord::getCourseName).filter(Objects::nonNull).distinct().count();
            result.add(item);
        }
        // 按总时长倒序
        result.sort((a,b) -> Integer.compare(b.totalDurationMinutes == null?0:b.totalDurationMinutes, a.totalDurationMinutes == null?0:a.totalDurationMinutes));
        return result;
    }
}